package com.fh.shop.consumer;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.OrderDetail;
import com.fh.shop.config.MQConstant;
import com.fh.shop.mapper.IMemberMapper;
import com.fh.shop.mapper.IOrderDetailMapper;
import com.fh.shop.mapper.IProductMapper;
import com.fh.shop.message.PayMessage;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class PayConsumer {

    @Autowired
    private IMemberMapper memberMapper;
    @Autowired
    private IProductMapper productMapper;
    @Autowired
    private IOrderDetailMapper orderDetailMapper;

    //增加会员积分
    @RabbitListener(queues = MQConstant.payFanout.SCORE_QUEUE)
    public void scoreConsumer(String msg, Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //修改会员积分
        PayMessage payMessage = JSON.parseObject(msg, PayMessage.class);
        Long memberId = payMessage.getMemberId();
        try {
            //1积分=1元 积分上取整
            double score = Math.ceil(payMessage.getTotalPrice().doubleValue());
            memberMapper.updateScore(memberId,score);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改会员:{}的积分异常,错误信息:{}",memberId,e.getMessage());
        } finally {
            channel.basicAck(deliveryTag,false);
        }

    }

    //增加销量
    @RabbitListener(queues = MQConstant.payFanout.STOCK_QUEUE)
    public void stockConsumer(String msg, Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        PayMessage payMessage = JSON.parseObject(msg, PayMessage.class);
        try {
            //增加销量
            QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderId",payMessage.getOrderId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);
            orderDetails.forEach(x -> {
                Long count = x.getCount();
                Long productId = x.getProductId();
                productMapper.updateSales(productId,count);
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改商品销量异常,错误信息:{}",e.getMessage());
        } finally {
            channel.basicAck(deliveryTag,false);
        }

    }
}
